//
//  TTFactoryAddressViewController.m
//  TaoTuo
//
//  Created by 刘广 on 2020/3/23.
//  Copyright © 2020 刘广. All rights reserved.
//

#import "TTFactoryAddressViewController.h"
#import "TTManagerAddressViewCell.h"
#import "TTAddFactoryAddressViewController.h"
#import "TTAddressModel.h"
#import "LLSearchTextField.h"

static NSString *cellID = @"factory_address_cellID";

@interface TTFactoryAddressViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, copy) void(^selectBlock)(TTAddressModel *model);

@property (nonatomic, strong) LLSearchTextField *searchTF;  // 搜索框
///原数据
@property (nonatomic, strong) NSMutableArray *originArray;
///搜索
@property (nonatomic, assign) BOOL isSearch;

@end

@implementation TTFactoryAddressViewController

- (instancetype)initWithSelectBlock:(void (^)(TTAddressModel * _Nonnull))selectBlock
{
    if (self == [super init]) {
        self.selectBlock = selectBlock;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.page = 1;
    [self getFactoryAddress];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"工厂地址";
    @weakify(self)
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        self.page = 1;
        [self getFactoryAddress];
    }];
    
    self.tableView.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
        @strongify(self)
        self.page++;
        [self getFactoryAddress];
    }];
    
    [self setupHeaderView];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTManagerAddressViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    [cell setModel:self.dataArray[indexPath.row] isFactory:YES];
    @weakify(self)
    cell.deleteAddressBlock = ^(TTManagerAddressViewCell * _Nonnull currentCell) {
        @strongify(self)
        NSIndexPath *ip = [self.tableView indexPathForCell:currentCell];
        [self.dataArray removeObjectAtIndex:ip.row];
        if (self.dataArray.count == 0) {
            [self.tableView reloadData];
        } else {
            [self.tableView deleteRowAtIndexPath:ip withRowAnimation:UITableViewRowAnimationFade];
        }
    };
    cell.setDefaultAddressBlock = ^(TTAddressModel * _Nonnull model) {
        @strongify(self)
        for (TTAddressModel *am in self.dataArray) {
            if (am.IsDefault) {
                am.IsDefault = NO;
                break;
            }
        }
        [self.tableView reloadData];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    @weakify(self)
    return [tableView fd_heightForCellWithIdentifier:cellID cacheByIndexPath:indexPath configuration:^(TTManagerAddressViewCell *cell) {
        @strongify(self)
        [cell setModel:self.dataArray[indexPath.row] isFactory:YES];
    }];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.selectBlock) {
        
        TTAddressModel *model = self.dataArray[indexPath.row];
        self.selectBlock(model);
        [self.navigationController popViewControllerAnimated:YES];
        
    }
    
}

/// 获取工厂地址
- (void)getFactoryAddress
{
    NSMutableDictionary *dic = @{
        @"param.pageIndex" : @(self.page),
        @"param.pageSize" : @40
    }.mutableCopy;
    if (self.isSearch) {
        [dic setObject:_searchTF.text forKey:@"param.receiverName"];
    }
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getFactoryAddress_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        
        if (self.page == 1) {
            [self.dataArray removeAllObjects];
        }
        
        for (NSDictionary *dic in responseObject) {
            TTAddressModel *model = [TTAddressModel modelWithJSON:dic];
            [self.dataArray addObject:model];
        }
        
        [self setupFooterView];
        
        [self.tableView reloadData];
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        @strongify(self)
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    } showLoadingInView:self.tableView];
}

// 添加工厂
- (void)addFactoryAddress
{
    TTAddFactoryAddressViewController *addVC = [[TTAddFactoryAddressViewController alloc] init];
    [self.navigationController pushViewController:addVC animated:YES];
}

- (void)setupFooterView
{
    UIButton *btn = [UIButton createButtonWithTitle:@"添加工厂" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:18] backgroundColor:kMainColor target:self action:@selector(addFactoryAddress)];
    [self.view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(45);
        make.bottom.equalTo(self.mas_bottomLayoutGuideTop);
    }];
}


- (void)setupHeaderView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 40)];
    view.backgroundColor = [UIColor whiteColor];
    
    _searchTF = [[LLSearchTextField alloc] initWithFrame:CGRectMake(38, 5, self.view.width - 38 * 2, 30)];
    _searchTF.backgroundColor = UIColorHex(EDEBFF);
    _searchTF.delegate = self;
    _searchTF.placeholder = @"输入工厂名称";
    [view addSubview:_searchTF];
    
    [self.view addSubview:view];
    
    [[_searchTF.rac_textSignal distinctUntilChanged] subscribeNext:^(NSString * _Nullable x) {
        if (x.length == 0) {
            self.isSearch = NO;
            self.page = 1;
            [self.dataArray removeAllObjects];
            [self.dataArray addObjectsFromArray:self.originArray];
            [self.tableView reloadData];
        }
    }];
    
    
}


///搜索
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.originArray removeAllObjects];
    [self.originArray addObjectsFromArray:self.dataArray];
    self.isSearch = YES;
    self.page = 1;
    [self getFactoryAddress];
    
    [self.view endEditing:YES];
    
    return YES;
}



- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.emptyImageName = @"nodata";
        _tableView.emptyTitel = @"暂无工厂地址";
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TTManagerAddressViewCell class]) bundle:nil] forCellReuseIdentifier:cellID];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop).mas_offset(40);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideTop).mas_offset(-45);
        }];
    }
    return _tableView;
}



- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)originArray
{
    if (!_originArray) {
        _originArray = [NSMutableArray array];
    }
    return _originArray;
}

@end
